#pragma once

//winsock 2.0
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#pragma comment(lib, "Ws2_32.lib")


class ISocketServerDelegate
{
public:
	virtual bool OnData(char* request,int requestLength,char** response,int* length)=0; //return true to keep the connection alive
};


//http://msdn.microsoft.com/en-us/library/ms737593(v=vs.85).aspx
class SocketServer
{
public:
	SocketServer(int _port,ISocketServerDelegate& socketServerDelegate);
	virtual ~SocketServer(void);

	void Start();
	void Wait();
private:
	void CloseAllConnections();
	static DWORD WINAPI AcceptIncomingConnections(LPVOID lpParam);
	static DWORD WINAPI ListenToClient(LPVOID lpParam);

	struct SocketClient
	{
		SOCKET socket;
		HANDLE thread;
		DWORD threadId;
		SocketClient(ISocketServerDelegate& _delegate):
			socketServerDelegate(_delegate)
		{
		}
		SocketClient(const SocketClient& src):
			socketServerDelegate(src.socketServerDelegate)
		{
			socket=src.socket;
			thread=src.thread;
			threadId=src.threadId;
		}
		ISocketServerDelegate& socketServerDelegate;
	};
	vector<SOCKET> socketClients;
	
	int port;
	SOCKET listeningSocket;
	HANDLE socketMutex;
	HANDLE listeningThread;
	DWORD listeningThreadId;
	ISocketServerDelegate& rSocketServerDelegate;

};

